package com.kinroy.briefreport.service.serviceimpl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kinroy.briefreport.dto.Result;
import com.kinroy.briefreport.dto.TaskDto;
import com.kinroy.briefreport.dto.TaskStatistics;
import com.kinroy.briefreport.entity.HandOverNode;
import com.kinroy.briefreport.entity.Project;
import com.kinroy.briefreport.entity.Task;
import com.kinroy.briefreport.entity.User;
import com.kinroy.briefreport.enums.task.TaskPriority;
import com.kinroy.briefreport.enums.task.TaskStatus;
import com.kinroy.briefreport.enums.task.TaskType;
import com.kinroy.briefreport.mapper.HandOverNodeMapper;
import com.kinroy.briefreport.mapper.ProjectMapper;
import com.kinroy.briefreport.mapper.TaskMapper;
import com.kinroy.briefreport.mapper.UserMapper;
import com.kinroy.briefreport.service.IHandOverNodeService;
import com.kinroy.briefreport.service.IProjectService;
import com.kinroy.briefreport.service.ITaskService;
import com.kinroy.briefreport.service.IUserService;
import com.kinroy.briefreport.utils.UUIDJudgmentTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Array;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
public class TaskServiceImpl extends ServiceImpl<TaskMapper, Task> implements ITaskService {

    @Autowired
    private TaskMapper taskMapper;

    @Autowired
    private IHandOverNodeService nodeService;

    @Autowired
    private ProjectMapper ProjectMapper;

    /**
     * 获取到状态不是 3（已完成待测试）/4(测试通过)/6(任务关闭)的此人所有任务
     *
     * @param currentTaskHandlerId
     * @return
     */
    @Override
    public Result getMyTasks(Long currentTaskHandlerId) {
        //kinroy 2023.12.13 更新了业务逻辑
        if (currentTaskHandlerId != null) {
            List<Task> myTasks = taskMapper.getMyTasks(currentTaskHandlerId);
            return Result.ok(myTasks);
        }
        return Result.ok("暂无任务");

        /*LambdaQueryWrapper<Task> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(currentTaskHandlerId!=null&&currentTaskHandlerId!=0,Task::getCurrentTaskHandlerId,currentTaskHandlerId);
        List<Task> taskList = list(wrapper);
        if (taskList==null){
            return Result.ok("暂无任务");
        }
        return Result.ok(taskList);*/
    }


    /**
     * 左侧我的任务获取详情的显示接口
     *
     * @param taskId
     * @return
     */
    @Override
    public Result getTaskById(String taskId) {
        Task byId = getById(taskId);
        if (byId == null) {
            return Result.fail("详情获取失败！");
        }
        return Result.ok(byId);
    }

    /**
     * 将对应的数据id转换成对应的名称
     *
     * @param task
     * @return
     */
    @Override
    public Result translationOfTaskInformation(Task task) {
        TaskDto taskDto = new TaskDto();
        //没办法一条sql查出数据了，只能分几次进行查询
        String projectName;
        String currentTaskHandlerName;
        String createUserName;

        //todo:查不出数据，解决一下
        try {
            projectName = taskMapper.translationOfTaskInformationProjectName(task);
            //获取当前任务经办人姓名
            currentTaskHandlerName = taskMapper.translationOfTaskInformationUserName(task.getCurrentTaskHandlerId());
            //获取任务创建人姓名
            createUserName = taskMapper.translationOfTaskInformationUserName(task.getCreateUserId());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("解析失败！");
        }
        /*封装数据*/
        taskDto.setTaskId(task.getTaskId());
        taskDto.setCreateUserName(createUserName);
        taskDto.setProjectName(projectName);
        taskDto.setCurrentTaskHandlerName(currentTaskHandlerName);
        return Result.ok(taskDto);
    }

    /**
     * 修改任务经办人（管理员分配任务）
     * 并将任务状态变成 “处理中”
     *
     * @param taskId
     * @param changerHandlerUserId
     * @return
     */
    @Override
    @Transactional
    public Result editTaskHandlerUser(String taskId, Long changerHandlerUserId) {
        Boolean aBoolean;
        try {
            aBoolean = taskMapper.editTaskHandlerUser(taskId, changerHandlerUserId);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("未知错误！");
        }
        //kinroy 2023.12.15 任务状态转变创建任务流转节点
        Boolean node = null;
        try {
            Task byId = getById(taskId);
            node = nodeService.createNode(byId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (aBoolean && node) {
            return Result.ok();
        }
        return Result.fail("分配失败！");
    }

    /**
     * 提交任务状态，修改对应任务
     *
     * @param task
     * @return
     */
    @Override
    @Transactional
    public Result submitTask(Task task) {
        //1.将taskStatus转换成对应的状态代码
        switch (task.getTaskStatus()) {
            case 0:
                //创建未处理，把完成时间给清空
                task.setCompletionTime(null);
                break;
            case 1:
                //处理中，把完成时间给清空
                task.setCompletionTime(null);
                break;
            case 2:
                //挂起，把完成时间给清空
                task.setCompletionTime(null);
                break;
            case 3:
                //已完成待测试，设置完成时间
                task.setCompletionTime(LocalDateTime.now());
                break;
            case 4:
                //测试通过，设置一下完成时间
                task.setCompletionTime(LocalDateTime.now());
                break;
            case 5:
                //测试未通过，清空完成时间
                task.setCompletionTime(null);
                break;
            case 6:
                //任务关闭不做处理
                break;
            default:
                break;

        }

        //更改任务状态
        Boolean aBoolean = taskMapper.updateTaskStatus(task);

        Boolean node = false;
        if (aBoolean) {
            //任务状态修改，创建任务流转节点
            node = nodeService.createNode(task);
        }
        if (node && aBoolean) {
            return Result.ok();
        }
        return Result.fail("状态修改失败！");
    }

    /**
     * 任务打回，把当前任务状态设置为处理中，
     * 然后再把重开次数自增1，update一下数据
     *
     * @param task
     * @return
     */
    @Override
    @Transactional
    public Result taskRepulse(Task task) {
        //1.预见性判断
        if (task == null) {
            return Result.fail("任务为空！");
        }
        //2.修改任务状态
        task.setTaskStatus(TaskStatus.PROCESSING.getCode());
        int restartTimes = task.getRestartTimes();
        task.setRestartTimes(restartTimes + 1);
        //3.update当前任务
        boolean b = updateById(task);
        //4.任务状态转变，创建任务流转节点
        Boolean node = nodeService.createNode(task);
        if (b && node) {
            return Result.ok();
        }
        return Result.fail("打回任务失败！");
    }

    /**
     * 修改任务信息
     *
     * @param task
     * @return
     */
    @Override
    public Result editTask(Task task) {
        boolean b = updateById(task);
        if (b) {
            return Result.ok();
        }
        return Result.fail("修改任务信息失败");
    }

    /**
     * 通过用户id当作任务经办人，去查询db，获取到任务总数和
     * 任务完成数和任务关闭数： 绩效=（当前用户任务完成数+当前用户任务关闭数）/当前用户任务总数
     *
     * @param userId
     * @return
     */
    @Override
    public Double getPerformance(Long userId) {
        if (userId == 0) {
            return null;
        }
        int completedTasks = taskMapper.countCompletedTasks(userId);
        int allTasks = taskMapper.countAllTasksFormCurrentUser(userId);
        double performance = 0;
        try {
            if (completedTasks == 0 || allTasks == 0) {
                return performance;
            }
            performance = (double) completedTasks / (double) allTasks;
        } catch (Exception e) {
            e.printStackTrace();
            return Double.valueOf(performance);
        }
        // 创建DecimalFormat对象，指定格式
        DecimalFormat decimalFormat = new DecimalFormat("#.##");

        // 使用format方法将double值格式化为字符串
        String formattedValue = decimalFormat.format(performance);

        return Double.valueOf(formattedValue);
    }

    /**
     * 获取当前用户的完成任务的各种类型的任务数量
     *
     * @param userId
     * @return
     */
    @Override
    @Transactional
    public Map<String, Integer> getObtainDifferentTaskTypes(Long userId) {
        if (userId == 0) {
            return null;
        }
        Map<String, Integer> tasksList = new HashMap<>();
        int bugTaskNum = taskMapper.countTaskByType(userId, TaskType.BUG.getCode());
        int devTaskNum = taskMapper.countTaskByType(userId, TaskType.DEV.getCode());
        int testTaskNum = taskMapper.countTaskByType(userId, TaskType.TEST.getCode());
        int otherTaskNum = taskMapper.countTaskByType(userId, TaskType.OTHER.getCode());
        int optimizationTaskNum = taskMapper.countTaskByType(userId, TaskType.OPTIMIZATION.getCode());
        tasksList.put("bug", bugTaskNum);
        tasksList.put("dev", devTaskNum);
        tasksList.put("test", testTaskNum);
        tasksList.put("other", otherTaskNum);
        tasksList.put("optimization", optimizationTaskNum);
        return tasksList;
    }

    /**
     * 获取当前用户的完成任务的各种优先级的任务数量
     *
     * @param userId
     * @return
     */
    @Override
    public Map<String, Integer> getObtainDifferentTaskPriority(Long userId) {
        if (userId == 0) {
            return null;
        }
        Map<String, Integer> taskList = new HashMap<>();
        for (int taskPriorityNum = 0; taskPriorityNum < 4; taskPriorityNum++) {
            int countTaskPriority = taskMapper.countTaskByPriority(userId, taskPriorityNum);
            switch (taskPriorityNum) {
                case 0:
                    taskList.put("低级", countTaskPriority);
                    break;
                case 1:
                    taskList.put("中级", countTaskPriority);
                    break;
                case 2:
                    taskList.put("高级", countTaskPriority);
                    break;
                case 3:
                    taskList.put("紧急", countTaskPriority);
                    break;
            }
        }
        return taskList;
    }

    /**
     * 获取当前用户的任务图表数据，封装后返回给前端展示
     *
     * @param userId
     * @return
     */
    @Override
    @Transactional
    public Result getTaskStatistics(Long userId) {
        TaskStatistics taskStatistics = new TaskStatistics();
        //1.获取待办任务数
        int undoTasks = taskMapper.countUndoTasks(userId);
        taskStatistics.setMyToDoTasksNum(undoTasks);
        //2.获取已完成的所有任务数
        int completedTasks = taskMapper.countCompletedTasks(userId);
        taskStatistics.setMyAllDoneTaskNum(completedTasks);
        //3.获取本周完成的任务数 （要传入本周的开始时间，和本周的结束时间）
       /* // 获取当前时间
        Calendar calendar = Calendar.getInstance();

        // 将日期设置为本周的开始日期，即周一
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);

        // 获取本周开始的时间戳
        Timestamp startOfWeek = new Timestamp(calendar.getTimeInMillis());

        // 将日期设置为本周的结束日期，即周日
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);*/

        // 获取当前日期
        LocalDate currentDate = LocalDate.now();

        // 获取本周的开始日期（周一）
        LocalDate startOfWeek = currentDate.with(DayOfWeek.MONDAY);

        // 获取本周的结束日期（周日）
        LocalDate endOfWeek = currentDate.with(DayOfWeek.SUNDAY);

        // 格式化日期
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String startDate = startOfWeek.format(formatter);
        String endDate = endOfWeek.format(formatter);

        int countTaskByThisWeek = taskMapper.countTaskByThisWeek(userId, startDate, endDate);
        taskStatistics.setWeekDoneTaskNum(countTaskByThisWeek);
        //4.获取个人绩效（当任务为空的时候，统计绩效部分会发生异常）
        Double performance = this.getPerformance(userId);
        taskStatistics.setPersonalPerformance(performance);

        //5.获取当前用户的完成任务的级别分布
        Map<String, Integer> obtainDifferentTaskPriority = this.getObtainDifferentTaskPriority(userId);
        taskStatistics.setAllTaskPriorityNum(obtainDifferentTaskPriority);

        //6.获取当前用户的完成任务的每周级别分布
        List<Task> taskListByThisWeek = taskMapper.getTaskListByThisWeek(userId, startDate, endDate);
        //key为任务的优先级，value为int数组，表示周一到周日的完成的任务数
        Map<String, Integer[]> result = new HashMap<>();
        Integer[] lowArr = {0, 0, 0, 0, 0, 0, 0};
        Integer[] midArr = {0, 0, 0, 0, 0, 0, 0};
        Integer[] highArr = {0, 0, 0, 0, 0, 0, 0};
        Integer[] urgentArr = {0, 0, 0, 0, 0, 0, 0};
        result.put("低", lowArr);
        result.put("中", midArr);
        result.put("高", highArr);
        result.put("紧急", urgentArr);
        for (Task task : taskListByThisWeek) {
            switch (task.getTaskPriority()) {
                case "0":
                    //表示当前task为低级任务
                    int dayValue = task.getCompletionTime().getDayOfWeek().getValue(); //1:周一 2：周二 以此类推
                    Integer[] days = result.get("低");
                    Integer day = days[dayValue - 1];
                    days[dayValue - 1] = day + 1;
                    result.put("低", days);
                    break;
                case "1":
                    //表示当前task为中级任务
                    int dayValue1 = task.getCompletionTime().getDayOfWeek().getValue(); //1:周一 2：周二 以此类推
                    Integer[] days1 = result.get("中");
                    Integer day1 = days1[dayValue1 - 1];
                    days1[dayValue1 - 1] = day1 + 1;
                    result.put("中", days1);
                    break;
                case "2":
                    //表示当前task为高级任务
                    int dayValue2 = task.getCompletionTime().getDayOfWeek().getValue(); //1:周一 2：周二 以此类推
                    Integer[] days2 = result.get("高");
                    Integer day2 = days2[dayValue2 - 1];
                    days2[dayValue2 - 1] = day2 + 1;
                    result.put("高", days2);
                    break;
                case "3":
                    //表示当前task为紧急任务
                    int dayValue3 = task.getCompletionTime().getDayOfWeek().getValue(); //1:周一 2：周二 以此类推
                    Integer[] days3 = result.get("紧急");
                    Integer day3 = days3[dayValue3 - 1];
                    days3[dayValue3 - 1] = day3 + 1;
                    result.put("紧急", days3);
                    break;
            }
        }
        taskStatistics.setWeekTaskPriorityNum(result);
        return Result.ok(taskStatistics);
    }

    /**
     * 获取当前用户的所有任务并实现分页功能
     * 页面一开始即加载
     *
     * @param userId      当前用户id
     * @param currentPage 当前页码
     * @param pageSize    页面数据条数
     * @return
     */
    @Override
    public Result getUserAllTaskByPage(Long userId, Long currentPage, Long pageSize, String taskStatus) {
        LambdaQueryWrapper<Task> taskLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //判断taskStatus,对应的状态码为：uodo: 0,1,5/ done:3,4,6  /handUp:2  /all:0,1,2,3,4,5,6
        switch (taskStatus) {
            case "undo":
                List<Integer> undoTaskStatus = Arrays.asList(0, 1, 5);
                taskLambdaQueryWrapper.in(Task::getTaskStatus, undoTaskStatus);
                break;
            case "done":
                List<Integer> doneTaskStatus = Arrays.asList(3, 4, 6);
                taskLambdaQueryWrapper.in(Task::getTaskStatus, doneTaskStatus);
                break;
            case "handUp":
                taskLambdaQueryWrapper.eq(Task::getTaskStatus, 2);
                break;
            default:
                break;
        }
        taskLambdaQueryWrapper.eq(userId != null, Task::getCurrentTaskHandlerId, userId);
        Page<Task> taskPage = new Page<>(currentPage, pageSize);
        Page<Task> page = this.page(taskPage, taskLambdaQueryWrapper);
        //获取到我想要返回给前端的数据：1.数据总数  2.当前页面数据数
        List<Task> records = page.getRecords();
        long total = page.getTotal();
        Map<String, Object> reslut = new HashMap<>();
        reslut.put("pageData", records);
        reslut.put("totalData", total);
        return Result.ok(reslut);
    }

    /**
     * 根据查询条件获取当前用户的任务数据并分页
     *
     * @param userId
     * @param currentPage
     * @param pageSize
     * @param taskStatus
     * @param projectSelectValue
     * @param taskTypeSelectValue
     * @param taskPrioritySelectValue
     * @return
     */
    @Override
    public Result getTaskConditionalQueryByPage(Long userId, Long currentPage,
                                                Long pageSize, String taskStatus,
                                                String projectSelectValue,
                                                String taskTypeSelectValue,
                                                String taskPrioritySelectValue) {

        LambdaQueryWrapper<Task> taskLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //判断taskStatus,对应的状态码为：uodo: 0,1,5/ done:3,4,6  /handUp:2  /all:0,1,2,3,4,5,6
        switch (taskStatus) {
            case "undo":
                List<Integer> undoTaskStatus = Arrays.asList(0, 1, 5);
                taskLambdaQueryWrapper.in(Task::getTaskStatus, undoTaskStatus);
                break;
            case "done":
                List<Integer> doneTaskStatus = Arrays.asList(3, 4, 6);
                taskLambdaQueryWrapper.in(Task::getTaskStatus, doneTaskStatus);
                break;
            case "handUp":
                taskLambdaQueryWrapper.eq(Task::getTaskStatus, 2);
                break;
            default:
                break;
        }
        taskLambdaQueryWrapper.eq(userId != null, Task::getCurrentTaskHandlerId, userId);

        //1.设置查询条件：所属项目，为空则不设置
        taskLambdaQueryWrapper.eq(projectSelectValue != null && projectSelectValue != "", Task::getProjectId, projectSelectValue);
        //2.设置查询条件：任务类型 有bug再这里

        if (StrUtil.isNotBlank(taskTypeSelectValue)) {
            taskLambdaQueryWrapper.eq(Task::getTaskType, Integer.valueOf(taskTypeSelectValue));
        }

        //3.设置查询条件：任务优先级
        taskLambdaQueryWrapper.eq(taskPrioritySelectValue != null && taskPrioritySelectValue != "", Task::getTaskPriority, taskPrioritySelectValue);

        //4.kinroy 2024.1.8 修改业务：返回的分页数据按照创建时间排序降序desc排序返回
        taskLambdaQueryWrapper.orderByDesc(Task::getCreateTime);
        //分页并返回
        Page<Task> taskPage = new Page<>(currentPage, pageSize);
        Page<Task> page = this.page(taskPage, taskLambdaQueryWrapper);
        //获取到我想要返回给前端的数据：1.数据总数  2.当前页面数据数
        List<Task> records = page.getRecords();
        long total = page.getTotal();
        Map<String, Object> reslut = new HashMap<>();
        reslut.put("pageData", records);
        reslut.put("totalData", total);
        return Result.ok(reslut);
    }

    /**
     * 通过任务id精确获取当前用户的任务
     * 和通过任务名称模糊匹配多条任务并且分页返回
     *
     * @param selectValue
     * @param userId
     * @param currentPage
     * @param pageSize
     * @param taskStatus
     * @param projectSelectValue
     * @param taskTypeSelectValue
     * @param taskPrioritySelectValue
     * @return
     */
    @Override
    public Result selectTaskByIdOrName(String selectValue,
                                       Long userId,
                                       Long currentPage,
                                       Long pageSize,
                                       String taskStatus,
                                       String projectSelectValue,
                                       String taskTypeSelectValue,
                                       String taskPrioritySelectValue) {

        LambdaQueryWrapper<Task> taskLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //判断taskStatus,对应的状态码为：uodo: 0,1,5/ done:3,4,6  /handUp:2  /all:0,1,2,3,4,5,6
        switch (taskStatus) {
            case "undo":
                List<Integer> undoTaskStatus = Arrays.asList(0, 1, 5);
                taskLambdaQueryWrapper.in(Task::getTaskStatus, undoTaskStatus);
                break;
            case "done":
                List<Integer> doneTaskStatus = Arrays.asList(3, 4, 6);
                taskLambdaQueryWrapper.in(Task::getTaskStatus, doneTaskStatus);
                break;
            case "handUp":
                taskLambdaQueryWrapper.eq(Task::getTaskStatus, 2);
                break;
            default:
                break;
        }
        taskLambdaQueryWrapper.eq(userId != null, Task::getCurrentTaskHandlerId, userId);
        //先判断前端传来的selectValue是任务id还是任务名称，任务id就是eq查询，任务名称就是like模糊查询
        //todo:uuid校验抛出异常了，解决一下
        try {
            if (UUIDJudgmentTool.uuidMatch(selectValue)) {
                //传入的查询条件为uuid，则是id精确查询
                taskLambdaQueryWrapper.eq(Task::getTaskId, selectValue);

            } else {
                //传入的查询条件不是uuid，则为任务名称模糊查询
                taskLambdaQueryWrapper.like(Task::getTaskName, selectValue);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("查询条件没有传入！");
        }

        //1.设置查询条件：所属项目，为空则不设置
        taskLambdaQueryWrapper.eq(projectSelectValue != null && projectSelectValue != "", Task::getProjectId, projectSelectValue);
        //2.设置查询条件：任务类型 有bug再这里

        if (StrUtil.isNotBlank(taskTypeSelectValue)) {
            taskLambdaQueryWrapper.eq(Task::getTaskType, Integer.valueOf(taskTypeSelectValue));
        }

        //3.设置查询条件：任务优先级
        taskLambdaQueryWrapper.eq(taskPrioritySelectValue != null && taskPrioritySelectValue != "", Task::getTaskPriority, taskPrioritySelectValue);

        //4.kinroy 2024.1.8 修改业务：返回的分页数据按照创建时间排序降序desc排序返回
        taskLambdaQueryWrapper.orderByDesc(Task::getCreateTime);

        //分页并返回
        Page<Task> taskPage = new Page<>(currentPage, pageSize);
        Page<Task> page = this.page(taskPage, taskLambdaQueryWrapper);
        //获取到我想要返回给前端的数据：1.数据总数  2.当前页面数据数
        List<Task> records = page.getRecords();
        long total = page.getTotal();
        Map<String, Object> reslut = new HashMap<>();
        reslut.put("pageData", records);
        reslut.put("totalData", total);
        return Result.ok(reslut);
    }

    /**
     * 项目管理员及以上的查询任务数据
     * 条件查询+管理的项目的任务+分页
     *
     * @param userId
     * @param currentPage
     * @param pageSize
     * @param taskStatus
     * @param projectSelectValue
     * @param taskTypeSelectValue
     * @param taskPrioritySelectValue
     * @return
     */
    @Override
    public Result getTaskConditionalQueryByPageForManager(Long userId, Long currentPage, Long pageSize, String taskStatus, String projectSelectValue, String taskTypeSelectValue, String taskPrioritySelectValue) {
        LambdaQueryWrapper<Task> taskLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //判断taskStatus,对应的状态码为：uodo: 0,1,5/ done:4,6  /handUp:2  /all:0,1,2,3,4,5,6  /unTest: 3
        switch (taskStatus) {
            case "undo":
                List<Integer> undoTaskStatus = Arrays.asList(0, 1, 5);
                taskLambdaQueryWrapper.in(Task::getTaskStatus, undoTaskStatus);
                break;
            case "done":
                List<Integer> doneTaskStatus = Arrays.asList(4, 6);
                taskLambdaQueryWrapper.in(Task::getTaskStatus, doneTaskStatus);
                break;
            case "handUp":
                taskLambdaQueryWrapper.eq(Task::getTaskStatus, 2);
                break;
            case "unTest":
                taskLambdaQueryWrapper.eq(Task::getTaskStatus, 3);
                break;
            case "testFailed":
                taskLambdaQueryWrapper.eq(Task::getTaskStatus, 5);

            default:
                break;
        }

        /* taskLambdaQueryWrapper.eq(userId != null, Task::getCurrentTaskHandlerId, userId);*/
        //设置查询条件默认展示出当前用户所管理的项目
        if (projectSelectValue == null || projectSelectValue == "") {
            List<Project> userManagerProjectList = ProjectMapper.getUserManagerProjectList(userId);
            List<String> managerProjectIds = new ArrayList<>();
            for (Project project : userManagerProjectList) {
                String projectId = project.getProjectId();
                managerProjectIds.add(projectId);
            }
            taskLambdaQueryWrapper.in(Task::getProjectId, managerProjectIds);
        }

        //1.设置查询条件：所属项目，为空则不设置
        taskLambdaQueryWrapper.eq(projectSelectValue != null && projectSelectValue != "", Task::getProjectId, projectSelectValue);
        //2.设置查询条件：任务类型 有bug再这里

        if (StrUtil.isNotBlank(taskTypeSelectValue)) {
            taskLambdaQueryWrapper.eq(Task::getTaskType, Integer.valueOf(taskTypeSelectValue));
        }

        //3.设置查询条件：任务优先级
        taskLambdaQueryWrapper.eq(taskPrioritySelectValue != null && taskPrioritySelectValue != "", Task::getTaskPriority, taskPrioritySelectValue);

        //4.kinroy 2024.1.8 修改业务：返回的分页数据按照创建时间排序降序desc排序返回
        taskLambdaQueryWrapper.orderByDesc(Task::getCreateTime);
        //分页并返回
        Page<Task> taskPage = new Page<>(currentPage, pageSize);
        Page<Task> page = this.page(taskPage, taskLambdaQueryWrapper);
        //获取到我想要返回给前端的数据：1.数据总数  2.当前页面数据数
        List<Task> records = page.getRecords();
        long total = page.getTotal();
        Map<String, Object> reslut = new HashMap<>();
        reslut.put("pageData", records);
        reslut.put("totalData", total);
        return Result.ok(reslut);
    }

    /**
     * 添加任务功能
     *
     * @param createUserId
     * @param task
     * @return
     */
    @Override
    @Transactional
    public Result addTask(Long createUserId, Task task) {
        //1.前端表单数据已经封装了部分任务信息，我们还需要封装的信息有（taskId，taskStatus，taskHandOverPath,）
        //除了流转节点路径，先将任务存入db，后调用handOverSevice 来实现实现任务节点的创建
        task.setCreateUserId(createUserId);
        /*List<HandOverNode> handOverNodesPath = new ArrayList<>();
        String handOverNodesPathJsonString = JSON.toJSONString(handOverNodesPath);
        task.setTaskHandOverPath(handOverNodesPathJsonString);*/

        //kinroy 2024.1.31 修复前端传来的日期不正确的问题
        LocalDateTime deadlineTime = task.getDeadlineTime();
        LocalDateTime localDateTime = deadlineTime.plusDays(1);
        LocalDateTime time = localDateTime.toLocalDate().atStartOfDay();
        task.setDeadlineTime(time);

        task.setTaskStatus(TaskStatus.CREATE_UNPROCESSED.getCode()); //设置默认状态为创建未处理
        task.setCurrentTaskHandlerId(createUserId); //设置刚创建的任务默认经办人为任务创建者
        boolean save = save(task);
        if (save) {
            LambdaQueryWrapper<Task> wrapper = new LambdaQueryWrapper<Task>();
            wrapper.eq(task.getTaskId() != null || task.getTaskId() != "", Task::getTaskId, task.getTaskId());
            Task one = getOne(wrapper);
            //创建任务流转节点
            Boolean node = nodeService.createNode(one);
            if (node) {
                return Result.ok();
            }
        }
        return Result.fail("添加任务失败！");

    }

    /**
     * 删除任务功能
     * 删除tb_task表中对应的taskId数据，同时删除tb_handovernode表中对应的taskId的流转节点数据
     *
     * @param taskId
     * @return
     */
    @Override
    @Transactional
    public Result delTask(String taskId) {
        boolean b = removeById(taskId);
        Boolean aBoolean = nodeService.removeAllNodeByTaskId(taskId);
        if (b&&aBoolean){
            return Result.ok();
        }
        return Result.fail("删除任务失败！");
    }


}
